import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/home_bar/home_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/lib_util.dart';

import '../../../../module_common/provider/wallet_info_provider.dart';
import '../../../../module_common/utils/util.dart';
import '../../../../module_common/widgets/button/public_button.dart';
import '../../../../module_common/widgets/dialog/bottom_sheet_widget.dart';
import '../../../../module_common/widgets/public_tip/public_tip.dart';
import '../../../../module_common/widgets/public_tip/validate_tip.dart';
import '../../provider/wallet_node_provider.dart';

class CustomNodeSheet extends StatefulWidget {
  const CustomNodeSheet({Key? key}) : super(key: key);

  @override
  _CustomNodeSheetState createState() => _CustomNodeSheetState();
}

class _CustomNodeSheetState extends State<CustomNodeSheet> {
  late Chain _chain;
  double sheetHeight = 0;
  String _nameError = '';
  String _linkError = '';
  TextEditingController _controllerName = TextEditingController();
  TextEditingController _controllerLink = TextEditingController();

  FocusNode _focusLink = FocusNode();
  FocusNode _focusName = FocusNode();
  bool _confirmEnable = false;
  bool _isCreating = false;

  @override
  void initState() {
    _controllerLink.text = '';
    _chain = context.read<WalletInfoNotifier>().walletChain!;

    _controllerName.addListener(() {
      checkConfirmEnable();
    });
    _controllerLink.addListener(() {
      checkConfirmEnable();
    });

    super.initState();
  }

  void checkConfirmEnable() {
    bool _enable = _controllerName.text.isNotEmpty && _controllerLink.text.isNotEmpty;

    if (_confirmEnable != _enable) {
      setState(() {
        _confirmEnable = _enable;
      });
    }
  }

  @override
  void dispose() {
    _controllerName.dispose();
    _controllerLink.dispose();
    _focusLink.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BottomSheetWidget(
        title: 'Custom Node',
        expand: false,
        child: Container(
          padding: EdgeInsets.only(left: 20, right: 20, top: 20),
          child: Column(
            children: [
              textInputControl(
                  height: 46.w,
                  inputFormatters: [
                    FilteringTextInputFormatter.allow(RegExp("[a-zA-Z0-9]")),
                    // 只允许输入英文大小写+数字
                    LengthLimitingTextInputFormatter(20)
                  ],
                  hintText: 'Please enter the node name',
                  controller: _controllerName,
                  focusNode: _focusName,
                  onFocus: () {
                    if (_controllerName.text.isEmpty) {
                      _nameError = 'Node name requires 1-20';
                    } else {
                      _nameError = '';
                    }
                  },
                  textInputAction: TextInputAction.next,
                  type: 1),
              Visibility(
                  visible: !_nameError.isEmpty,
                  child: ValidateTip(
                      text: _nameError,
                      margin: EdgeInsets.only(top: 10.w),
                      onClose: () {
                        setState(() {
                          _nameError = "";
                        });
                      })),
              SizedBox(height: 20),
              textInputControl(
                  height: 66,
                  // inputFormatters: [LengthLimitingTextInputFormatter(20)],
                  hintText: 'Please enter node link',
                  maxLines: null,
                  controller: _controllerLink,
                  focusNode: _focusLink,
                  textInputAction: TextInputAction.next,
                  type: 2),
              Visibility(
                  visible: !_linkError.isEmpty,
                  child: ValidateTip(
                      text: _linkError,
                      margin: EdgeInsets.only(top: 10.w),
                      onClose: () {
                        setState(() {
                          _linkError = "";
                        });
                      })),
              SizedBox(height: 20.w),
              Container(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                        child: PublicButton(
                            margin: EdgeInsets.zero,
                            type: ButtonType.defaultType,
                            text: 'Cancel',
                            onClick: () {
                              Navigator.of(context).pop();
                            })),
                    SizedBox(
                      width: 20.w,
                    ),
                    Expanded(
                        child: PublicButton(
                      margin: EdgeInsets.zero,
                      type: ButtonType.private,
                      disabledStatus: _controllerLink.text.isEmpty || _controllerName.text.isEmpty,
                      text: 'Confirm',
                      onClick: () async {
                        try {
                          if (_isCreating) {
                            return;
                          }
                          _isCreating = true;
                          //检查
                          RegExp regex = RegExp("^(http).*", caseSensitive: false);
                          if (regex.hasMatch(_controllerLink.text)) {
                            //请求节点，看一下通不通
                            var rate = await NodeRateUtils.getResponseTime(_controllerLink.text,_chain.shortName);
                            if (rate > 0) {
                              //通的
                              _linkError = '';
                            } else {
                              //不通
                              _linkError = 'Invalid link';
                            }
                          } else {
                            _linkError = 'Invalid link';
                          }

                          if (_controllerName.text.isEmpty) {
                            _nameError = 'Node name requires 1-20';
                          } else {
                            _nameError = '';
                          }
                          setState(() {});
                          if (_nameError.isEmpty && _linkError.isEmpty) {
                            if (ObjectBox().nodeInfoModel.getNodeInfo(_controllerLink.text) != null) {
                              Toast.hide();
                              Toast.show(context, message: 'RPC URL exists', status: '2', position: Dpositon.top);
                              _isCreating = false;
                              return;
                            }

                            //判断节点是否可用
                            var rate = await NodeRateUtils.getResponseTime(_controllerLink.text,_chain.shortName);
                            if (rate == 0) {
                              Toast.hide();
                              await Toast.show(context, message: 'RPC URL error', status: '2', position: Dpositon.top);
                              _isCreating = false;
                              return;
                            }
                            //添加当前的节点
                            context.read<NodeProvider>().addNode(
                                chain: _chain.shortName,
                                url: _controllerLink.text,
                                name: _controllerName.text,
                                isSelected: true);
                            Toast.hide();
                            await Toast.show(context, message: 'Operating succeeded');

                            Navigator.pop(context);
                          }
                          _isCreating = false;
                        } catch (e) {
                          _isCreating = false;
                          Toast.hide();
                          Toast.show(context, message: 'RPC URL error', status: '2', position: Dpositon.top);
                        }
                      },
                    ))
                  ],
                ),
              ),
              HomeBar()
            ],
          ),
        ));
  }

  Widget textInputControl(
      {double? height,
      List<TextInputFormatter>? inputFormatters,
      int? maxLines = 1,
      String hintText = '',
      FocusNode? focusNode,
      TextEditingController? controller,
      TextInputAction? textInputAction,
      void Function()? onEditingComplete,
      void Function()? onFocus,
      int type = 1}) {
    return Container(
      height: height,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.w),
        color: Color.fromRGBO(246, 246, 246, 1),
      ),
      child: Stack(
        children: [
          Row(
            children: [
              Expanded(
                  child: TextField(
                      cursorHeight: 20.w,
                      textInputAction: textInputAction,
                      inputFormatters: inputFormatters,
                      textAlign: TextAlign.justify,
                      textAlignVertical: TextAlignVertical.top,
                      controller: controller,
                      focusNode: focusNode,
                      onTapOutside: (PointDownEvent) {
                        focusNode?.unfocus();
                        onFocus != null ? onFocus() : '';
                      },
                      onEditingComplete: onEditingComplete,
                      onChanged: (value) {
                        setState(() {
                          controller!.text = value;
                          _linkError = '';
                          _nameError = '';
                        });
                        // 当选项卡正在发生切换时触发的操作】
                      },
                      maxLines: maxLines,
                      style: TextStyle(
                          color: Color.fromRGBO(51, 51, 51, 1),
                          fontWeight: FontWeight.w400,
                          fontSize: 14.sp,
                          height: 20.w / 14.w),
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.all(15.w),
                        border: InputBorder.none,
                        hintText: hintText,
                        hintStyle: TextStyle(
                          fontSize: 14.sp,
                          color: "#BEBDCA".toColor(),
                        ),
                      ))),
              SizedBox(
                width: type == 1 ? 60.w : 30.w,
              ),
            ],
          ),
          Positioned(
              right: 15,
              child: Container(
                height: height,
                alignment: Alignment.center,
                child: type == 1
                    ? Row(
                        children: [
                          Visibility(
                              visible: controller!.text.length > 0,
                              child: GestureDetector(
                                onTap: () {
                                  setState(() {
                                    controller.text = '';

                                    _nameError = '';
                                  });
                                },
                                child: Image.asset(
                                  'assets/images/common/clear-input.png',
                                  width: 16.w,
                                  height: 16.w,
                                ),
                              )),
                          SizedBox(
                            width: 10.w,
                          ),
                          Text(
                            '${controller.text.length}/20',
                            style: TextStyle(fontSize: 12.sp, fontWeight: FontWeight.w400, color: AppColors.c_BEBDCA),
                          )
                        ],
                      )
                    : Visibility(
                        visible: controller!.text.length > 0,
                        child: GestureDetector(
                          onTap: () {
                            setState(() {
                              controller.text = '';
                              _linkError = '';
                            });
                          },
                          child: Image.asset(
                            'assets/images/common/clear-input.png',
                            width: 16.w,
                            height: 16.w,
                          ),
                        )),
              ))
        ],
      ),
    );
  }
}
